// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Pan Haijun, Gang Chen(chengang12@baidu.com)
//
// This file realize the HttpClient class, it's used to establish http connection.
#include "baidu_http_client.h"
#include "mbed.h"
#include "baidu_mbed_soc_wrapper.h"
#include "duer_log.h"
#include "heap_monitor.h"

namespace duer {

HttpClient::HttpClient() :
        _p_client_inst(NULL) {
    socket_ops ops = {
        0,
        mbed_socket_init,
        mbed_socket_open,
        mbed_socket_connect,
        mbed_socket_set_blocking,
        mbed_socket_set_timeout,
        mbed_socket_recv,
        mbed_socket_send,
        mbed_socket_close,
        mbed_socket_destroy
    };

    _p_client_inst = (http_client_c*)MALLOC(sizeof(http_client_c), HTTP);
    if (!_p_client_inst) {
        DUER_LOGE("No enough memory!!!");
        return;
    }

    http_client_init(_p_client_inst);
    if (http_client_init_socket_ops(_p_client_inst, &ops, NULL) != HTTP_OK) {
        DUER_LOGE("Http client init socket ops failed!");
        return;
    }
}

HttpClient::~HttpClient() {
    if (_p_client_inst) {
        http_client_destroy(_p_client_inst);
        FREE(_p_client_inst);
    }
}

void HttpClient::register_data_handler(data_out_handler_cb data_hdlr_cb, void* p_usr_ctx) {
    if (!_p_client_inst) {
        return;
    }

    http_client_reg_data_hdlr_cb(_p_client_inst, data_hdlr_cb, p_usr_ctx);
}

void HttpClient::register_notify_call_back(check_stop_notify_cb_t chk_stp_cb) {
    if (!_p_client_inst) {
        return;
    }

    http_client_reg_stop_notify_cb(_p_client_inst, chk_stp_cb);
}

void HttpClient::register_call_back_to_get_url(get_url_cb_t cb) {
    if (!_p_client_inst) {
        return;
    }

    http_client_reg_cb_to_get_url(_p_client_inst, cb);
}

void HttpClient::get_download_progress(size_t* total_size, size_t* recv_size) {
    if (!_p_client_inst || !total_size || !recv_size) {
        return;
    }

    http_client_get_download_progress(_p_client_inst, total_size, recv_size);
}

int HttpClient::get(const char* url, const size_t pos) {
    if (!_p_client_inst) {
        return HTTP_FAILED;
    }

    return http_client_get(_p_client_inst, url, pos);
}


}//duer

